import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_learn_vi/src/page/train/train_course_item_director_widget.dart';
import 'package:flutter_learn_vi/src/page/train/train_synthesize_check_report_details.dart';
import 'package:flutter_learn_vi/src/page/train/train_teacher_course_item_widget4.dart';
import 'package:get/get.dart';

import '../../bean/bean_train.dart';
import '../../bean/bean_video_course.dart';
import '../../utils/color_utils.dart';
import '../../utils/string_utils.dart';
import '../common/common_loading_dialog.dart';
import '../common/common_nodata_widget.dart';
import 'controller/director_teacher_work_log_controller.dart';
import 'controller/eacher_work_train_details_controller.dart';
import 'director_teacher_work_add_page.dart';
import 'director_teacher_work_log_list_page.dart';

///班主任的培训 详情
class DirectorWorkTrainDetailsPage extends StatefulWidget {
  final String tag;

  final int trainId;

  const DirectorWorkTrainDetailsPage(
      {Key key, @required this.tag, @required this.trainId})
      : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _DirectorWorkTrainDetailsPageState();
  }
}

class _DirectorWorkTrainDetailsPageState
    extends State<DirectorWorkTrainDetailsPage>
    with SingleTickerProviderStateMixin {
  TeacherTrainDetailsController _historyController;
  TabController _tabController;

  @override
  void initState() {
    super.initState();
    _historyController = Get.put(
      TeacherTrainDetailsController(trainId: widget.trainId),
      tag: widget.tag,
    );
    _tabController = new TabController(length: 2, vsync: this);

    Future.delayed(Duration.zero, () async {
      await _historyController.requestDetailsFunction();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("培训详情"),
      ),
      body: GetBuilder(
        id: "root",
        tag: widget.tag,
        builder: (TeacherTrainDetailsController controller) {
          return Container(
              padding: EdgeInsets.only(top: 10),
              child: NestedScrollView(
                body: buildListView(),
                headerSliverBuilder:
                    (BuildContext context, bool innerBoxIsScrolled) {
                  return [
                    SliverToBoxAdapter(
                      child: buildTrainBase(),
                    ),
                  ];
                },
              ));
        },
      ),
    );
  }

  Widget buildTrainBase() {
    TrainBean _trainBean = _historyController.getTrainBean();
    if (_trainBean == null) {
      return SizedBox();
    }

    int trainStatus = _trainBean.trainStatus;

    String statuesStr = "";
    Color textColor = Colors.blueGrey;
    if (trainStatus == 5) {
      textColor = Colors.green;
      statuesStr = "进行中";
    } else if (trainStatus == 6) {
      statuesStr = "已完成";
      textColor = Colors.green;
    } else if (trainStatus == 9) {
      statuesStr = "未开始";
      textColor = Colors.grey;
    } else if (trainStatus == 102) {
      statuesStr = "培训未开始";
      textColor = Colors.grey;
    } else if (trainStatus == 101) {
      statuesStr = "培训已结束";
      textColor = Colors.grey;
    }
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(10),
      child: Card(
        child: Padding(
          padding: EdgeInsets.all(10),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              Row(
                children: [
                  buildLeftTitle("培训名称"),
                  Expanded(
                    child: Text(
                      "${_trainBean.trainName}",
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  )
                ],
              ),
              SizedBox(height: 8),
              Row(
                children: [
                  buildLeftTitle("培训状态"),
                  Expanded(
                    child: Text(
                      "${statuesStr}",
                      style: TextStyle(
                        fontSize: 14,
                        color: textColor,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  )
                ],
              ),
              SizedBox(height: 8),
              Row(
                children: [
                  buildLeftTitle("培训时间"),
                  SizedBox(
                    width: 10,
                  ),
                  Expanded(
                    child: Text(
                      "${_trainBean.startStudyTime} ~ ${_trainBean.endStudyTime}",
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                  )
                ],
              ),
              SizedBox(
                height: 8,
              ),
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  buildLeftTitle("培训简介"),
                  SizedBox(
                    width: 10,
                  ),
                  Expanded(
                    child: GestureDetector(
                      onLongPress: () {
                        if (_trainBean.trainRemark != null &&
                            _trainBean.trainRemark.length > 50) {
                          Get.defaultDialog(
                            radius: 4,
                            title: "培训简介",
                            content: Container(
                              constraints: BoxConstraints(maxHeight: 600),
                              child: SingleChildScrollView(
                                child: Text(_trainBean.trainRemark),
                              ),
                            ),
                            confirm: Container(
                              alignment: Alignment.center,
                              child: TextButton(
                                onPressed: () {
                                  Get.back(result: true);
                                },
                                child: Text(
                                  "确认",
                                  style: TextStyle(color: Colors.blue),
                                ),
                              ),
                              width: 100,
                            ),
                          );
                        }
                      },
                      child: Text(
                        "${_trainBean.trainRemark ?? "--"}",
                        maxLines: 4,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.w400,
                        ),
                      ),
                    ),
                  )
                ],
              ),
              SizedBox(height: 8),
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  buildLeftTitle("参与部门"),
                  Expanded(
                    child: Container(
                      margin: EdgeInsets.only(top: 2),
                      child: Wrap(
                        runSpacing: 10,
                        children: buildDepartment(_trainBean),
                      ),
                    ),
                  )
                ],
              ),
              SizedBox(
                height: 8,
              ),
              Container(
                child: buildControllerButton(_trainBean),
              ),
            ],
          ),
        ),
      ),
    );
  }

  buildControllerButton(TrainBean trainBean) {
    if (trainBean == null) {
      return SizedBox();
    }
    if (trainBean.teacherDirectorId == null) {
      return SizedBox();
    }
    int trainStatus = trainBean.trainStatus;
    return Wrap(
      children: [
        trainStatus == 5
            ? ElevatedButton(
                onPressed: () async {
                  await Get.to(
                    () => DirectorTeacherWorkLogAddPage(trainBean: trainBean),
                  );
                  if (Get.isRegistered<DirectorTeacherWorkLogController>(
                      tag: "train")) {
                    Get.find<DirectorTeacherWorkLogController>(tag: "train")
                        .requestListFunction();
                  }
                },
                child: Text(" 新增班主任日志"),
              )
            : SizedBox(),
        SizedBox(
          width: 12,
        ),
        ElevatedButton(
          onPressed: () async {
            await Get.to(
              () => DirectorTeacherWorkLogListPage(
                trainId: trainBean.trainId,
                tag: 'mine2',
              ),
            );
          },
          child: Text(" 查询工作日志"),
        ),
        SizedBox(
          width: 12,
        ),
        ElevatedButton(
          onPressed: () async {
            await Get.to(
              () => TrainSynthesizeCheckReportDetails(
                trainId: trainBean.trainId,
                tag: 'mine2',
              ),
            );
          },
          child: Text(" 查看培训报告"),
        ),
      ],
    );
  }

  Widget buildLeftTitle(String title) {
    return Container(
      width: 68,
      child: Text("$title"),
    );
  }

  ///参与的部门
  List<Widget> buildDepartment(TrainBean trainBean) {
    String department = trainBean.selectDepartment;
    if (StringUtils.isEmpty(department)) {
      return [buildDepartMentCell("全部部门")];
    } else {
      if (department.contains(",")) {
        List<String> list = department.split(",");
        List<Widget> widgetList = [];
        list.forEach((element) {
          widgetList.add(buildDepartMentCell(element));
        });
        return widgetList;
      } else {
        return [buildDepartMentCell("$department")];
      }
    }
  }

  Widget buildDepartMentCell(String title) {
    return Stack(
      alignment: Alignment.center,
      children: [
        Container(
          margin: EdgeInsets.only(right: 10),
          padding: EdgeInsets.only(left: 6, right: 6, top: 1, bottom: 2),
          decoration: BoxDecoration(
              color: ColorUtils.getRandomColor(),
              borderRadius: BorderRadius.all(Radius.circular(20))),
          child: Text(
            "$title",
            style: TextStyle(color: Colors.white, fontSize: 9),
          ),
        )
      ],
    );
  }

  AnimatedSwitcher buildAnimatedSwitcher(BuildContext context) {
    return AnimatedSwitcher(

        //动画执行切换时间
        duration: const Duration(milliseconds: 200),
        //动画构建器 构建指定动画类型
        transitionBuilder: (Widget child, Animation<double> animation) {
          //执行缩放动画
          return FadeTransition(child: child, opacity: animation);
        },
        //执行动画的子 Widget
        //只有子 Widget 被切换时才会触发动画
        child: buildCourseAndTeacher());
  }

  Widget buildCourseAndTeacher() {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(10),
      child: Card(
        child: Padding(
          padding: EdgeInsets.all(10),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            mainAxisSize: MainAxisSize.min,
            children: [
              Row(
                children: [
                  Container(
                    width: 4,
                    height: 14,
                    margin: EdgeInsets.only(right: 8),
                    color: Colors.blueAccent,
                  ),
                  Expanded(
                    child: Text(
                      "培训内容",
                      style: TextStyle(
                        fontSize: 14,
                      ),
                    ),
                  )
                ],
              ),
              SizedBox(
                height: 8,
              ),
              Expanded(
                child: NestedScrollView(
                  body: buildListView(),
                  headerSliverBuilder:
                      (BuildContext context, bool innerBoxIsScrolled) {
                    return [];
                  },
                ),
              ),
              SizedBox(
                height: 10,
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget buildListView() {
    bool loading = _historyController.getIsLoading();
    if (loading) {
      return Center(
        child: LoadingWidget(),
      );
    }
    TrainBean _trainBean = _historyController.getTrainBean();
    if (_trainBean == null) {
      return Center(child: NoDataWidget());
    }
    int count = 0;
    if (_trainBean.courseList != null) {
      count = _trainBean.courseList.length;
    }
    if (_trainBean.videoCourseEntityList != null) {
      count = count + _trainBean.videoCourseEntityList.length;
    }

    return Container(
      padding: EdgeInsets.all(12),
      color: Colors.white,
      child: ListView.separated(
        physics: BouncingScrollPhysics(),
        shrinkWrap: true,
        itemCount: count,
        itemBuilder: (BuildContext context, int index) {
          if (_trainBean.courseList != null &&
              index < _trainBean.courseList.length) {
            CourseAndTeacherBean cubean;
            cubean = _trainBean.courseList[index];
            return TrainTeacherCourseItemWidget4(
              cubean: cubean,
              index: index,
            );
          }

          BeanVideoCourse beanVideoCourse = _trainBean
              .videoCourseEntityList[index - _trainBean.courseList.length];
          return TrainCourseVideoItemDirectorWidget(
            videoCourse: beanVideoCourse,
            index: index,
            trainId: _trainBean.trainId,
          );
        },
        separatorBuilder: (BuildContext context, int index) {
          return Divider();
        },
      ),
    );
  }
}
